package org.garbagecan.hibernatestudy.util;

import java.net.URL;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaUpdate;


public class HibernateSessionFactory {

	private static Log log = LogFactory.getLog(HibernateSessionFactory.class);

	private static HibernateSessionFactory hibernateSessionFactory;

	private SessionFactory sessionFactory;

	private HibernateSessionFactory() {
		init();
	}

	public static HibernateSessionFactory getInstance() {
		if (hibernateSessionFactory == null) {
			hibernateSessionFactory = new HibernateSessionFactory();
		}
		return hibernateSessionFactory;
	}

	public Session getSession() throws HibernateException {
		return this.sessionFactory.openSession();
	}

	public void closeSession(Session session) {
		if (session != null) {
			try {
				session.close();
			}
			catch (HibernateException he) {
				log.fatal("close the session Exception!", he);
			}
		}
	}

	private void init() {
		log.info("HibernateSessionFactory Init ...");
		Configuration conf = null;
		URL url = null;
		try {
			conf = new Configuration().configure();

			sessionFactory = conf.buildSessionFactory();

			//new SchemaExport(conf).create(true, true);
			new SchemaUpdate(conf).execute(true, true);

		} catch (MappingException e) {
			e.printStackTrace();
			log.error("", e);
		} catch (HibernateException e) {
			e.printStackTrace();
			log.error("", e);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("", e);
		}
	}
}
